/*
 * Copyright (c) 2013 WDCY Information Technology Co. Ltd
 * www.wdcy.cc
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * WDCY Information Technology Co. Ltd ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with WDCY Information Technology Co. Ltd.
 */
package com.monkey.web.platform.service.impl;

import com.monkey.core.domain.icon.Icon;
import com.monkey.core.domain.icon.IconRepository;
import com.monkey.core.domain.icon.IconType;
import com.monkey.core.service.BaseServiceImpl;
import com.monkey.utils.MonkeyUtils;
import com.monkey.web.platform.service.IconService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Wu Tianqiang
 */
@Service
public class IconServiceImpl extends BaseServiceImpl<Icon, Long> implements IconService {

    @Autowired
    private IconRepository iconRepository;

    @Override
    public void synIcons(HttpServletRequest request) {
        String root = request.getSession().getServletContext().getRealPath("/");
        List<Icon> notExistedIcons = findNotExistedIcons(root, IconType.SIZE16);
        notExistedIcons.addAll(findNotExistedIcons(root, IconType.SIZE64));
        if (MonkeyUtils.isNotEmpty(notExistedIcons)) {
            iconRepository.save(notExistedIcons);
        }
    }

    private List<Icon> findNotExistedIcons(String root, IconType iconType) {
        File directory = new File(root + "/resources/icons/" + iconType.getLabel());
        List<Icon> icons = new ArrayList<>();
        String[] files = directory.list();
        if (MonkeyUtils.isNotEmpty(files)) {
            for (String name : files) {
                if (!existedByNameAndIconType(name, iconType)) {
                    icons.add(buildIcon(name, iconType));
                }
            }
        }
        return icons;
    }

    private Icon buildIcon(String iconName, IconType iconType) {
        Icon icon = new Icon();
        icon.setName(iconName);
        icon.setIconType(iconType);
        return icon;
    }

    @Override
    public boolean existedByNameAndIconType(String name, IconType iconType) {
        Long amount = iconRepository.countByNameAndIconType(name, iconType);
        return amount != 0;
    }


}